<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Lib/Base.php';
require_once __DIR__ . '/funcs.php';
require_once __DIR__ . '/Lib/Page.php';

checkLogin();
checkFunc(67);

$now = time();
$success = $_GET['success'] ?? null;
$error = $_GET['error'] ?? null;
$action = $_GET['action'] ?? null;

$table_id = 2;

$have_ranking = $active_rank_reward = [];
$active_rank_reward_db = $DB->get('active_rank', 'val', ['id'=>$table_id]);
$coupon_arr = $DB->select('game_sign_coupon',['id','coupon_name','batch_number']);
if ($active_rank_reward_db){
    $active_rank_reward = json_decode( $active_rank_reward_db, true );
    $have_ranking = array_column($active_rank_reward, 'ranking');

    foreach ($active_rank_reward as $key => $item){
        $active_rank_reward[$key]['batch'] = '';
        // $reward = json_decode($item['reward'],true);
        foreach ($item['reward'] as $val){
            if (isset($val['extra'])){
                $active_rank_reward[$key]['batch'] = $val['extra'];
            }
        }
    }
}

$action = $_GET['action'] ?? null;
if($action == 'edit') {
    echo '<pre>';
    checkFunc(68, '权限不足，无法操作');

    $ranking = $_POST['rank'] ?? 0;
    $siliao = $_POST['siliao'] ?? '';
    $yhq = $_POST['yhq'] ?? '';
    $star = $_POST['star'] ?? '';

    if ($yhq) $yhq = implode(',',$yhq);

    $reward_arr = ['ranking'=>$ranking, 'reward'=> []];
    if($siliao > 0) $reward_arr['reward'][] = [ 'num'=>intval($siliao), 'type'=>1, 'id'=>1];
    if($star > 0) $reward_arr['reward'][] = [ 'num'=>intval($star), 'type'=>6, 'id'=>6];
    if($yhq) $reward_arr['reward'][] = [ 'extra'=>$yhq, 'type'=>2];
    $active_rank_reward[$ranking] = $reward_arr;
    $edit_data = ['id' => $table_id, 'name'=>'排行奖励', 'val'=> json_encode($active_rank_reward), 'time'=> $now ];

    if(empty($active_rank_reward_db)) {
        // 新增
        $DB->insert('active_rank', $edit_data);
        operate_log('active_rank', 'edit_reward', ['配置奖励'=>json_encode($reward_arr),]);
        goExit('active_rank_reward.php?success=签到奖励新增成功');
    } else {
        // 修改
        $res = $DB->update('active_rank', $edit_data, ['id'=>$table_id]);
        operate_log('active_rank', 'edit_reward', ['配置奖励'=>json_encode($active_rank_reward),]);
        goExit('active_rank_reward.php?success=签到奖励修改成功');
    }
    exit;
}

display_header();

$all_item = $DB->select('game_item', '*');
// $item_types = [1=>'饲料', 2=>'批次号', 5=>'装扮', '6'=>'星星'];
$all_items = [];
foreach($all_item as $i) {
    $all_items[$i['id']] = $i;
}
?>
<link href="css/jquery.dm-uploader.min.css" rel="stylesheet">
<style>
    .valid_task {background:#ffe; /* #C2ECA7 */;}
    #fileinp{
        position: absolute;
        left: 0;
        top: 0;
        opacity: 0;
    }
</style>

<section class="content">

    <?php display_title('活跃度排行榜奖励配置'); ?>

    <?php if($error) : ?>
        <div class="alert alert-warning alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
            <span><?php echo $error; ?></span>
        </div>
    <?php endif ?>
    <?php if($success) : ?>
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
            <h4><i class="icon fa fa-check"></i> 成功</h4>
            <?php echo $success; ?>
        </div>
    <?php endif ?>

    <div class="box box-warning">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-tasks"></i> 排名奖励列表</h3>
        </div>
        <div class="box-body">
            <button type="button" class="btn btn-primary pull-left add_reward_form" style="margin-bottom:10px;">添加奖励</button>

            <table id="logtable" class="table table-bordered table-striped dataTable table-hover table-condensed" role="grid" aria-describedby="example1_info">
                <thead>
                <tr>
                    <th class="center" width="100">排名</th>
                    <th class="center" width="400">奖励</th>
                    <th class="center">操作</th>
                </tr>
                </thead>
                <tbody>
                <?php
                foreach($active_rank_reward as $info) {
                    ?>
                    <tr role="row" style="height:38px;text-align:center;">
                        <td class="font12">
                            <span class="tid" style="font-size:16px;font-weight:bold;"><?php echo $info['ranking']; ?></span>
                        </td>
                        <td class="font12 left">
                            <span style="display:none" class="sreward"><?php echo json_encode($info['reward']); ?></span>
                            <?php
                            $task_reward = $info['reward'];
                            echo '<ul style="margin:0;padding:0;margin-left:20px;">';
                            foreach($task_reward as $tw) {
                                if($tw['type'] == 1) {
                                    echo '<li>' . $all_items[$tw['id']]['name'] . ' * ' . $tw['num'] . '</li>';
                                } else if($tw['type'] == 2) {
                                    echo '<li>批次号<ul style="margin:0;padding:0;margin-left:40px;">';
                                    $ex_arr = explode(',', $tw['extra']);
                                    foreach($ex_arr as $ex) {
                                        echo '<li>' . $ex . '</li>';
                                    }
                                    echo '</ul></li>';
                                } else if($tw['type'] == 6) {
                                    echo '<li>' . $all_items[$tw['id']]['name'] . ' * ' . $tw['num'] . '</li>';
                                }
                            }
                            echo '</ul>';
                            ?>
                        </td>
                        <input type="hidden" class="item_batch" value="<?php echo $info['batch'] ?>">
                        <td class="left" style="padding:0;padding-left:15px;" ranking="<?php echo $info['ranking']; ?>">
                            <button class="btn btn-primary btn-sm edit_reward">修改</button>
                        </td>
                    </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 修改奖励 -->
    <div class="modal fade" id="modal-edit-reward">
        <div class="modal-dialog modal-lg">
            <form id="edit_reward_form" action="active_rank_reward.php?action=edit" method="post" onsubmit="return sub()">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title"></h4>
                    </div>
                    <div class="modal-body">
                        <table border="0" width="100%" class="modal_table_style">
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">排名:</th>
                                <td><input type="number" class="form-control" size="20" name="rank" id="rank" /></td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">
                                    奖励饲料:
                                    <br><span style="color:#999;font-weight:normal;font-size:12px;">无饲料奖励请留空</span>
                                </th>
                                <td>
                                    <input type="number" class="form-control" style="display:inline;width:300px;" size="20" name="siliao" id="siliao" />
                                </td>
                            </tr>
                            <tr height="45">
                                <th width="150" style="text-align:right;padding-right:10px;">
                                    奖励星星:
                                    <br><span style="color:#999;font-weight:normal;font-size:12px;">无星星奖励请留空</span>
                                </th>
                                <td>
                                    <input type="number" class="form-control" style="display:inline;width:300px;" size="20" name="star" id="star" />
                                </td>
                            </tr>
                            <tr height="45">
                                <th style="text-align:right;padding-right:10px;">可使用优惠券:</th>
                                <td style="font-size:12px;">
                                    <div class="funcs_box" style="overflow-y:scroll;height:100px;padding:5px 10px; margin:10px 0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;border-left:1px solid #ccc;">
                                        <?php
                                        echo '<div class="pull-left">';
                                        foreach ($coupon_arr as $val){
                                            echo '<label style="margin-right:15px;display:inline-block;">';
                                            echo '<input type="checkbox" name="yhq[]" value="'.$val['batch_number'].'"> ';
                                            echo $val['coupon_name'];
                                            echo '</label>';
                                        }
                                        echo '</div>';
                                        echo '<div style="clear:both"></div>';
                                        echo '</div>';
                                        ?>
                                    </div>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary submit_form">确定</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

</section>

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/pace.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Select2 -->
<script src="bower_components/select2/dist/js/select2.full.min.js"></script>
<!-- InputMask -->
<script src="plugins/input-mask/jquery.inputmask.js"></script>
<script src="plugins/input-mask/jquery.inputmask.date.extensions.js"></script>
<script src="plugins/input-mask/jquery.inputmask.extensions.js"></script>
<!-- SlimScroll -->
<script src="bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- iCheck 1.0.1 -->
<script src="plugins/iCheck/icheck.min.js"></script>
<!-- FastClick -->
<script src="bower_components/fastclick/lib/fastclick.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/adminlte.min.js"></script>
<script type="text/javascript">
    $(function() {
        $('.add_reward_form').click(function() {
            $('.modal-title').text('添加奖励');
            $('#rank').val('');
            $('#edit_id').val('');
            $('#modal-edit-reward').modal({
                backdrop: 'static',
            });
        });

        $('.submit_form').click(function() {
            $('#edit_reward_form').submit();
        });
        $('.edit_reward').click(function() {
            $('.modal-title').text('修改奖励');
            $('#rank').val($(this).parent().attr('ranking'));
            var treward = $(this).parent().parent().find('.sreward').text();
            var rewards = JSON.parse(treward);
            // console.log(rewards);
            for(i in rewards) {
                if(rewards[i]['type'] == 1) {
                    $('#siliao').val(rewards[i]['num']);
                } else if(rewards[i]['type'] == 2) {
                    // $('#yhq').val(rewards[i]['extra']);
                } else if(rewards[i]['type'] == 6) {
                    $('#star').val(rewards[i]['num']);
                }
            }
            var batch = $(this).parent().parent().find('.item_batch').val();
            batch_arr = batch.split(',');
            $('input[type=checkbox]').each(function () {
                let checked = false;
                let val = $(this).val();
                if ($.inArray(val.toString(),batch_arr) > -1){
                    checked = true;
                }
                $('input:checkbox[value='+val+']').prop('checked',checked);
            });

            $('#modal-edit-reward').modal({
                backdrop: 'static',
            });
        });

        setTimeout(function() {
            $('.alert-success').fadeOut();
            if($('.alert-warning').find('span').html() && $('.alert-warning').find('span').html().length < 60) {
                $('.alert-warning').fadeOut();
            }
        }, 2000);
    });

    function sub() {
        let yhq = $('#yhq').val();
        let coupon_id = $('input[type=checkbox]:checked').val();
        if(yhq && !coupon_id){
            alert('请勾选优惠券');
            return false;
        }
        return true;
    }
</script>

</body>
</html>
